<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>鸡兔同笼问题</title>
        <link rel="stylesheet" href="test03.css">
    </head>
    <body>
        <div class="container">
            <h2>循环解决鸡兔同笼问题</h2>
            <p>鸡兔同笼，鸡兔一共 <input type="number" id="totalAnimals" placeholder="总动物数" > 只。笼子里脚一共 <input type="number" id="totalFeet" placeholder="总脚数"> 只，请问分别有多少只鸡和兔？
                <button onclick="solveProblem()">计算</button>
            </p>
            <p id="result"></p>
        </div>
    
        <script>
            function solveProblem() {
                const totalAnimals = parseInt(document.getElementById('totalAnimals').value);
                const totalFeet = parseInt(document.getElementById('totalFeet').value);
                const resultElement = document.getElementById('result');
    
                if (isNaN(totalAnimals) || isNaN(totalFeet)) {
                    resultElement.textContent = '请输入有效的数字！';
                    return;
                }
    
                for (let chickens = 0; chickens <= totalAnimals; chickens++) {
                    const rabbits = totalAnimals - chickens;
                    const feet = chickens * 2 + rabbits * 4;
    
                    if (feet === totalFeet) {
                        resultElement.textContent = `分别有鸡 ${chickens} 只，有兔子 ${rabbits} 只。`;
                        return;
                    }
                }
    
                resultElement.textContent = '无解！';
            }
        </script>
    </body>
    </html>